package com.ruoyi.teaching.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.PlatformUResource;
import com.ruoyi.teaching.domain.UniversalCreateUpdate;
import com.ruoyi.teaching.domain.VettingRequest;
import com.ruoyi.teaching.domain.vo.PlatformUResourceVO;
import com.ruoyi.teaching.domain.vo.modelFileInfoVO;
import com.ruoyi.teaching.mapper.PlatformUResourceMapper;
import com.ruoyi.teaching.service.PlatformUResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-06-26
 */
@Service
public class PlatformUResourceServiceImpl extends ServiceImpl<PlatformUResourceMapper, PlatformUResource> implements PlatformUResourceService {
    @Autowired
    private PlatformUResourceMapper platformUResourceMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    private static final String DOWNLOAD_COUNT_KEY = "resource_download_count";


    @Override
    public AjaxResult selectPlatformUResourceListOwn(Integer pageNum, Integer pageSize, Integer resourceType, Integer vettingStatus, String resourceName) {
        QueryWrapper<PlatformUResource> wrapper = new QueryWrapper<>();
        Page<PlatformUResource> page = new Page<>(pageNum, pageSize);
        int userId = SecurityUtils.getUserId().intValue();
        wrapper.eq("create_id", userId);
        if (null != resourceType) {
            wrapper.eq("resource_type", resourceType);
        }
        if (null != vettingStatus) {
            wrapper.eq("vetting_status", vettingStatus);
        }
        if (null != resourceName && !resourceName.equals("")) {
            wrapper.like("resource_name", resourceName);
        }
        wrapper.orderByDesc("id");
        Page<PlatformUResource> page1 = platformUResourceMapper.selectPage(page, wrapper);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page1);
    }

    @Override
    public AjaxResult selectPlatformUResourceListSystemAdmin(Integer pageNum, Integer pageSize, Integer resourceType, Integer vettingStatus, String resourceName) {
        QueryWrapper<PlatformUResource> wrapper = new QueryWrapper<>();
        Page<PlatformUResource> page = new Page<>(pageNum, pageSize);
        if (null != resourceType) {
            wrapper.eq("resource_type", resourceType);
        }
        if (null != resourceName && !resourceName.equals("")) {
            wrapper.like("resource_name", resourceName);
        }
        if (null != vettingStatus) {
            wrapper.eq("vetting_status", vettingStatus);
        }
        wrapper.orderByDesc("id");
        Page<PlatformUResource> page1 = platformUResourceMapper.selectPage(page, wrapper);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page1);
    }

    /**
     * 查询用户资源列表
     *
     * @param pageNum      页码
     * @param pageSize     每页条数
     * @param resourceType 资源类型（0文档，1图片，2视频，3课件，4模型素材）
     * @param specialtyId  专业大类
     * @param resourceName 资源名称
     * @param sortord      排序方式（0默认先按下载量再按上传时间，1按下载量）
     * @return AjaxResult   查询结果
     */
    @Override
    public AjaxResult selectPlatformUResourceListUser(Integer pageNum, Integer pageSize, Integer resourceType, Integer specialtyId, String resourceName, Integer sortord) {
        QueryWrapper<PlatformUResource> wrapper = new QueryWrapper<>();

        // 按资源类型过滤
        if (resourceType != null && resourceType != 999) {
            wrapper.eq("resource_type", resourceType);
        }

        // 按专业大类过滤
        if (specialtyId != null && specialtyId != 999) {
            wrapper.eq("specialty_id", specialtyId);
        }

        // 按资源名称过滤
        if (resourceName != null && !resourceName.isEmpty()) {
            wrapper.like("resource_name", resourceName);
            // 记录搜索词，类型为"1资源"
            redisCache.recordSearchTerm(1, resourceName);
        }

        // 只查询已审核通过的资源
        wrapper.eq("vetting_status", 1);

        // 执行查询
        List<PlatformUResource> resourceList = platformUResourceMapper.selectList(wrapper);

        // 获取Redis中的下载量并排序
        Map<Long, Integer> downloadCountMap = new HashMap<>();
        for (PlatformUResource resource : resourceList) {
            Integer downloadCount = redisCache.getCacheMapValue(DOWNLOAD_COUNT_KEY, resource.getId().toString());
            resource.setDownloadCount(downloadCount);
            downloadCountMap.put(resource.getId(), downloadCount != null ? downloadCount : 0);
        }

        // 根据下载量排序
        resourceList.sort((r1, r2) -> {
            // 从下载量映射表中获取两个资源的下载量
            int count1 = downloadCountMap.getOrDefault(r1.getId(), 0);
            int count2 = downloadCountMap.getOrDefault(r2.getId(), 0);

            // 判断排序方式
            return sortord != null && sortord == 1
                    // 如果排序方式为1，直接按下载量降序排列
                    ? Integer.compare(count2, count1)
                    // 否则，首先按下载量降序排列；如果下载量相同，再按创建时间从新到旧排序
                    : (count2 != count1
                    ? Integer.compare(count2, count1)
                    : r2.getCreateTime().compareTo(r1.getCreateTime()));
        });


        // 分页处理
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, resourceList.size());
        List<PlatformUResource> paginatedList = resourceList.subList(start, end);

        // 将分页结果转换为 Page 对象
        Page<PlatformUResource> page = new Page<>(pageNum, pageSize);
        page.setRecords(paginatedList);
        page.setTotal(resourceList.size());

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page);
    }


    @Override
    public AjaxResult selectPlatformUResourceById(Long id) {
        PlatformUResource platformUResource = platformUResourceMapper.selectById(id);
        PlatformUResourceVO platformUResourceVO = new PlatformUResourceVO();
        BeanUtils.copyProperties(platformUResource, platformUResourceVO);
        platformUResourceVO.setModelUrlArray(JSONArray.parseArray(platformUResource.getModelUrl(), modelFileInfoVO.class));
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformUResourceVO);
    }


    @Override
    public AjaxResult insertPlatformUResource( PlatformUResourceVO platformUResourceVO) {
        PlatformUResource platformUResource = new PlatformUResource();
        BeanUtils.copyProperties(platformUResourceVO,platformUResource);
        UniversalCreateUpdate create = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformUResource.setCreateBy(create.getName());
        platformUResource.setCreateTime(DateUtils.getNowDate());
        platformUResource.setCreateId(create.getId());
        platformUResource.setUploadPerson(create.getName());
        String topLevelSchoolName = UniversalUtil.findTopLevelSchoolName(sysUserRoleMapper, sysDeptMapper, sysUserMapper, null);
        if (!"".equals(topLevelSchoolName)) {
            platformUResource.setUploadPersonSchool(topLevelSchoolName);
        }
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            // 未登录用户，按普通用户处理
        } catch (ServiceException e) {

        }
        int roleId = 0;
        if (userId != null) {
            roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        }
        boolean roleSystemAdmin = (roleId == 1 || roleId == 6);// 超级管理员
        if (roleSystemAdmin) {
            platformUResource.setVettingStatus(1);
        } else {
            platformUResource.setVettingStatus(0);
        }
        int insert = platformUResourceMapper.insert(platformUResource);
        if (insert > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "添加成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "添加失败");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformUResourceByIds(Long[] ids) {
        int length = ids.length;
        int i = platformUResourceMapper.deleteBatchIds(Arrays.asList(ids));
        if (length == i) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public AjaxResult updatePlatformUResourceVetting(VettingRequest vettingRequest) {
        PlatformUResource platformUResource = new PlatformUResource();
        BeanUtils.copyProperties(vettingRequest, platformUResource);
        long l = vettingRequest.getId().longValue();
        platformUResource.setId(l);
        platformUResource.setUpdateTime(DateUtils.getNowDate());
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformUResource.setUpdateBy(update.getName());
        platformUResource.setUpdateId(update.getId());
        int u = platformUResourceMapper.updateById(platformUResource);
        if (u > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "审核成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "审核失败，请联系管理员");
        }
    }

    @Override
    public void updatePlatformUResourceDownload(Long resourceId) {
        redisCache.getIncrementValue(DOWNLOAD_COUNT_KEY, resourceId.toString(), 1);
    }

    @Override
    public AjaxResult selectHotSearch() {
        Set<Object> top5SearchTerms = redisCache.getTop5SearchTerms(1);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", top5SearchTerms);
    }
}
